package com.sparrow.common.hotswap2;

import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

public class SafepointManager {
    private final AtomicInteger safepointCount = new AtomicInteger(0);
    private final CountDownLatch safepointLatch = new CountDownLatch(1);

    /**
     * 创建全局安全点
     */
    public void createGlobalSafepoint() throws InterruptedException {
        int count = safepointCount.incrementAndGet();
        if (count == 1) {
            // 第一个请求安全点，暂停所有模块处理
            pauseAllModules();
            safepointLatch.countDown();
        } else {
            // 等待安全点建立
            safepointLatch.await();
        }
    }

    /**
     * 释放全局安全点
     */
    public void releaseGlobalSafepoint() {
        int count = safepointCount.decrementAndGet();
        if (count == 0) {
            // 最后一个安全点请求，恢复处理
            resumeAllModules();
        }
    }

    private void pauseAllModules() {
        // 暂停所有业务模块处理
    }

    private void resumeAllModules() {
        // 恢复所有业务模块处理
    }

    /**
     * 检查是否在安全点中
     */
    public boolean isInSafepoint() {
        return safepointCount.get() > 0;
    }
}
